# -*- coding: utf-8 -*-
import hashlib
import json
import random
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'M1007': {
        # 秒接支付  支付宝 3% 10—5000 witch
        # 秒接支付  微信扫码 3.5% 200—5000 witch
        'API_KEY': 'jVwKESnPOTRI6g01d9eGEi7N2',
        'gateway': 'http://pay.miaojiepay.com/ZFPayApi.aspx',
        'query_gateway': 'http://pay.miaojiepay.com/OrderSelectInterface.aspx',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("miaojiepay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 微信扫码：pay_weixin_scan
# 支付宝扫码：pay_alipay_scan
# qq扫码：pay_qqpay_scan
# 微信wap：pay_weixin_wap
# 支付宝wap：pay_alipay_wap
# qqWAP：pay_qqpay_wap
# 网银：pay_note_wap
# 银联快捷：pay_ylpay_wap
# 银联扫码：pay_ylpay_scan
def _get_pay_type(service):
    if service == 'alipay_scan':
        return 'pay_alipay_scan'
    elif service == 'alipay_wap':
        return 'pay_alipay_wap'
    elif service == 'wechat_scan':
        return 'pay_weixin_scan'
    elif service == 'wechat_wap':
        return 'pay_weixin_wap'
    else:
        return 'pay_weixin_scan'


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    service = info['service']  # wechat or alipay
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('subject', 'charge'),
        ('total_fee', int(pay_amount * 100)),
        ('pay_type', _get_pay_type(service)),
        ('mchNo', app_id),
        ('body', 'charge'),
        ('version', '2.0'),
        ('showurl', '{}/pay/api/{}/miaojiepay/{}/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('mchorderid', str(pay.id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)

    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    parameter_dict['client_ip'] = user_info.get('device_ip') or '127.0.0.1'
    parameter_dict['callback_url'] = '{}/pay/api/{}/miaojiepay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH,
                                                                          app_id)
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    json_data = json.dumps(parameter_dict, separators=(',', ':'))
    _LOGGER.info('miaojiepay create charge params: %s', json_data)
    response = requests.post(_get_gateway(app_id), data=json_data, headers=headers, timeout=15)
    _LOGGER.info('miaojiepay create charge rsp: %s, %s', response.text, response.url)
    if response.status_code == 200:
        resp = json.loads(response.text)
        pay_url = resp.get('code_url') or resp.get('code_img_url')
        charge_resp.update({
            'charge_info': pay_url,
        })
    else:
        _LOGGER.warn('miaojiepay data error, status_code: %s', response.status_code)
    return charge_resp


def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    _LOGGER.info("miaojiepay notify data: %s", data)
    api_key = _get_api_key(app_id)
    verify_notify_sign(data, api_key)
    pay_id = data['mchorderid']
    if not pay_id:
        _LOGGER.error("fatal error, miaojiepay out_trade_no not exists, data: %s" % data)
        raise ParamError('miaojiepay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_no = data['pdorderid']
    total_fee = float(data['total_fee']) / 100

    if total_fee != float(pay.total_fee):
        _LOGGER.warn('pay %s price invalid %s != %s', pay_id, total_fee, pay.total_fee)

    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    if discount:
        assert (total_fee / discount) >= 20
    extend = {
        'discount': discount,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    _LOGGER.info('miaojiepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
    res = order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
    # async notify
    async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    charge_resp = {}
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mchNo', app_id),
        ('mchorderid', str(pay_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    _LOGGER.info("miaojiepay query data is: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['mchorderid'])
    response = requests.post(_get_query_gateway(app_id), data=json.dumps(parameter_dict, separators=(',', ':')),
                             headers=headers,
                             timeout=3)
    _LOGGER.info("miaojiepay query rsp is: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_no = pay_order.third_id
        trade_status = int(data['status'])
        total_fee = float(data['total_fee']) / 100

        discount = float(json.loads(pay_order.extend or '{}').get('discount', 0))
        if discount:
            assert (total_fee / discount) >= 20
        extend = {
            'discount': discount,
            'trade_status': trade_status,
            'total_fee': total_fee
        }

        if trade_status == 1:
            _LOGGER.info('miaojiepay query order success, mch_id:%s pay_id:%s',
                         pay_order.mch_id, pay_order.id)
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('miaojiepay data error, status_code: %s', response.status_code)
    return charge_resp
